#This script sends the desired output files via email to the user registered with the email designated below.
#Files should then be placed in "weather" folder in the project's working directory

#clear environment 
rm(list = ls())
library(httr)
library(jsonlite)
library(lubridate)
library(xml2)
options(stringsAsFactors = FALSE)

#set directories
WORK.DIRECTORY = "Z:/user/rih4/Solar Siting/JAERE Code Repository"
DATA.DIRECTORY = file.path(WORK.DIRECTORY,"Data JAERE")
WORK.OUT = file.path(DATA.DIRECTORY,"intermediate_output")
PLOT.OUT = file.path(DATA.DIRECTORY, "final_output")
dir.create(WORK.OUT);dir.create(PLOT.OUT, recursive=T)

url <- "http://developer.nrel.gov"
path <- "api/solar/nsrdb_psm3_download.json"
#path <- "api/solar/nsrdb/site_count.format" #path for counting the number of sites
key <- "INSERT_YOUR_API_KEY_HERE"
name <- "YOUR NAME GOES HERE"
email <- "YOUR_EMAIL@XYZ.EDU"
affiliation <- "YOUR INSTITUTION"
purpose <- "Academic"
attributes <- "air_temperature,dew_point,dhi,dni,surface_albedo,wind_speed"

zip.geo <- read.csv(file.path(DATA.DIRECTORY,"zipcode_centroid_latlon_3-27-2018.csv"))

vec.length <- 223
#seq(1,nrow(zip.geo)%/%vec.length)
for(i in seq(1,nrow(zip.geo)%/%vec.length)){
  lat <- zip.geo$latitude[((i-1)*vec.length):(i*vec.length)]
  long <- zip.geo$longitude[((i-1)*vec.length):(i*vec.length)]
  mylist <- ""
  for(j in 1:vec.length){
    mylist <- paste(mylist,paste(long[j], lat[j], sep = " "),sep = ", ")
  }
  mylist <- substring(mylist,3) #drops the first comma and space from the string
  wkt <- paste("MULTIPOINT(",mylist,")",sep="")
  raw.result <- GET(url = url, path=path, query = list(api_key = key,full_name=name,email=email,affiliation=affiliation,reason=purpose,mailing_list="false",wkt=wkt,names="tmy",attributes=attributes,leap_day="false",utc="false",interval=60))
  result <- content(raw.result)
}




